package com.dkm.nettysocketdemo.myWebsite.service.impl;

import com.dkm.nettysocketdemo.myWebsite.dao.HelmetImgMapper;
import com.dkm.nettysocketdemo.myWebsite.domain.HelmetImg;
import com.dkm.nettysocketdemo.myWebsite.service.HelmetImgService;
import com.dkm.nettysocketdemo.untils.FileTools;
import com.dkm.nettysocketdemo.untils.redis.RedisOperator;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName : HelmetImgServiceImpl  //类名
 * @Description : 安全帽图片服务接口  //描述
 * @Author : 易嵘  //作者
 * @Date: 2021-03-23 09:54  //时间
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class HelmetImgServiceImpl implements HelmetImgService {

    /**
     * 图片服务接口
     */
    @Resource
    HelmetImgMapper imgMapper;

    /**
     * 文件工具类
     */
    @Resource
    FileTools fileTools;

    @Resource
    RedisOperator redisOperator;

    Gson gson = new Gson();

    /**
     * 新增安全帽图片
     *
     * @param helmetId    安全帽id
     * @param helmetImage 安全帽图片
     * @return 回调函数
     */
    @Override
    public int addImage(String helmetId, MultipartFile helmetImage) {
        int row = 0;
        try {
            String path = fileTools.saveFile("helmetImg", helmetImage);
            HelmetImg img = new HelmetImg();
            img.setPkImgId(UUID.randomUUID().toString().replaceAll("-", ""));
            img.setImgUrl(path);
            img.setHelmetId(helmetId);
            row = imgMapper.insertSelective(img);
            if (row > 0) {
                redisOperator.lSet(helmetId + "ImgList", gson.toJson(img));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return row;
    }

    /**
     * 根据安全帽id查询图片
     *
     * @param helmetId 安全帽id
     * @return 图片集合
     */
    @Override
    public List<HelmetImg> findHelmetIdAll(String helmetId) {
        List<String> list = redisOperator.lGet(helmetId + "ImgList", 0, -1);
        List<HelmetImg> imgs = new LinkedList<>();
        if (ObjectUtils.isEmpty(list)) {
            imgs = imgMapper.findHelmetIdAll(helmetId);
            for (HelmetImg img : imgs) {
                redisOperator.lSet(helmetId + "ImgList", gson.toJson(img));
            }
        } else {
            for (String s : list) {
                HelmetImg img = gson.fromJson(s, HelmetImg.class);
                imgs.add(img);
            }
        }
        return imgs;
    }
}
